package thesis.filesharing.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import thesis.filesharing.bo.ClassBO;
import thesis.filesharing.bo.LecturerBO;
import thesis.filesharing.bo.SemesterBO;
import thesis.filesharing.bo.StudentBO;
import thesis.filesharing.bo.SubjectBO;
import thesis.filesharing.common.util.Utils;
import thesis.filesharing.common.valueobjects.SearchClassValueObject;
import thesis.filesharing.model.Clazz;
import thesis.filesharing.model.Lecturer;
import thesis.filesharing.model.Semester;
import thesis.filesharing.model.Student;
import thesis.filesharing.model.Subject;
import thesis.filesharing.resources.Constants;
import thesis.filesharing.services.fulltextsearch.indexing.DocumentIndexing;
import thesis.filesharing.services.fulltextsearch.indexing.DocumentQuery;
import thesis.filesharing.services.fulltextsearch.indexing.Operators;
import thesis.filesharing.services.fulltextsearch.indexing.QueryBuilder;
import thesis.filesharing.web.auth.AuthUtil;
import thesis.filesharing.web.util.PageInfo;
import thesis.filesharing.web.util.PropertiesUtil;
import thesis.filesharing.web.util.Util;
import thesis.filesharing.web.validator.CreateClassValidator;
import thesis.filesharing.web.validator.UpdateClassValidator;
import thesis.filesharing.web.viewmodel.CreateClassViewModel;
import thesis.filesharing.web.viewmodel.UpdateClassViewModel;
import thesis.filesharing.web.viewmodel.ajaxbeans.ClassBean;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.search.Field;
import com.google.appengine.api.search.Results;
import com.google.appengine.api.search.ScoredDocument;

@Controller
public class ClassController {
	
	@Autowired
	private ClassBO classBO;
	
	@Autowired
	private StudentBO studentBO;
	
	@Autowired
	private SubjectBO subjectBO;
	
	@Autowired
	private LecturerBO lecturerBO;
	
	@Autowired
	private SemesterBO semesterBO;
	
	@Autowired
	private CreateClassValidator createClassValidator;
	
	@Autowired
	private UpdateClassValidator updateClassValidator;
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/createClass", method = RequestMethod.GET)
	public String initCreateClassForm(ModelMap model) {
		CreateClassViewModel createClassViewModel = new CreateClassViewModel();
		model.addAttribute("createClassViewModel", createClassViewModel);
		return "admin/createClass";
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/createClass", method = RequestMethod.POST)
	public ModelAndView processCreateClassSubmit(
			@ModelAttribute("createClassViewModel") CreateClassViewModel createClassViewModel,
			BindingResult bindingResult, SessionStatus status, ModelMap model, HttpSession session) {
		
		createClassValidator.validate(createClassViewModel, bindingResult);
		
		if (bindingResult.hasErrors()) {
			return new ModelAndView("admin/createClass");
		} else {
			status.setComplete();
			
			Clazz c = new Clazz();
			c.setClassId(createClassViewModel.getClassId());
			c.setClassName(createClassViewModel.getClassName());
			c.setSemester(semesterBO.getCurrentSemester().getSemesterName());
			
			Subject s = subjectBO.findSubjectById(createClassViewModel.getSubjectId());
			
			if (createClassViewModel.getLecturerId() != null && createClassViewModel.getLecturerId().length() > 0) {
				Lecturer l = lecturerBO.findLecturerById(createClassViewModel.getLecturerId());
				if (l != null) {
					c.setLecturer(l);
				}
			}
			
			c = classBO.saveClass(c, s.getSubjectKey());
			DocumentIndexing.addEntityIndex(c, Constants.SEARCH_INDEX_NAME);
			
			session.setAttribute("msg", PropertiesUtil.getProperty("class.create.success"));
			return new ModelAndView(new RedirectView("/admin/listClasses.html"));
		}
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/listClasses", method = RequestMethod.GET)
	public String listClasses(@RequestParam(value = "p", required = false, defaultValue = "1") Integer p, ModelMap model) {
		SearchClassValueObject searchObj = new SearchClassValueObject(null, null, null, semesterBO.getCurrentSemester().getSemesterName());
		if (p < 1 || p > Util.calculateNumberOfPage(classBO.countFoundClasses(searchObj), Constants.PAGE_SIZE)) {
			p = 1;
		}
		List<Clazz> classes = classBO.searchClasses(searchObj, p, Constants.PAGE_SIZE);
		model.addAttribute("classes", classes);
		model.addAttribute("semesters", semesterBO.listSemester());
		model.addAttribute("pageInfo", new PageInfo(classBO.countFoundClasses(searchObj), p));
		model.addAttribute("pageSize", Constants.PAGE_SIZE);
		
		return "admin/listClasses";
	}
	
	@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_STUDENT')")
	@RequestMapping(value = "/searchClassInfoAjax", method = RequestMethod.GET)
	public void searchClassInfoAjax(@RequestParam("q") String q, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		
		q = Utils.insertSignChar(Utils.filterVietnameseSign(q));
		if (q.trim().length() > 0) {
			QueryBuilder builder = new QueryBuilder();
			String query = builder.add("fClassId", q, Operators.COLON)
					.or("fClassName", q, Operators.COLON)
					.buildQuery();
			
			Results<ScoredDocument> results = DocumentQuery.search(query, Constants.SEARCH_INDEX_NAME);
			List<ClassBean> classBeans = new ArrayList<ClassBean>();
			
			for (ScoredDocument result : results) {
				Iterator<Field> fields = result.getFields().iterator();
				
				Field f = null;
				String fieldName = null;
				ClassBean classBean = new ClassBean();
				classBean.setClassKey(result.getId());
				
				while (fields.hasNext()) {
					f = fields.next();
					fieldName = f.getName();
					
					if ("classId".equals(fieldName)) {
						classBean.setClassId(f.getText());
					} else if ("className".equals(fieldName)) {
						classBean.setClassName(f.getText());
					}
				}
				classBeans.add(classBean);
			}
			
			ObjectMapper mapper = new ObjectMapper();
			out.print(mapper.writeValueAsString(classBeans));
		} else {
			out.print("[]");
		}
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/updateClass/{key}", method = RequestMethod.GET)
	public String initUpdateClassForm(@PathVariable("key") String key, ModelMap model) {
		UpdateClassViewModel updateClassViewModel = new UpdateClassViewModel();
		Clazz c = classBO.findClassByKey(key);
		if (c != null) {
			updateClassViewModel.setClassKey(KeyFactory.keyToString(c.getClassKey()));
			updateClassViewModel.setClassId(c.getClassId());
			updateClassViewModel.setClassName(c.getClassName());
			updateClassViewModel.setSemester(c.getSemester());
			updateClassViewModel.setSubjectId(c.getSubject().getSubjectId());
			if (c.getLecturer() != null) {
				String l = c.getLecturer().getLecturerId();
				if (l != null && l.length() > 0) {
					updateClassViewModel.setLecturerId(l);
				}
			}
		}
		model.addAttribute("updateClassViewModel", updateClassViewModel);
		return "admin/updateClass";
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/updateClass/{key}", method = RequestMethod.POST)
	public ModelAndView processUpdateClassSubmit(
			@ModelAttribute("updateClassViewModel") UpdateClassViewModel updateClassViewModel,
			@RequestParam(value = "p", required = false, defaultValue = "1") Integer p,
			BindingResult bindingResult, SessionStatus status, ModelMap model, HttpSession session, HttpServletRequest request) {
		
		updateClassValidator.validate(updateClassViewModel, bindingResult);
		
		if (bindingResult.hasErrors()) {
			return new ModelAndView("admin/updateClass");
		} else {
			status.setComplete();
			Lecturer l = null;
			if (updateClassViewModel.getLecturerId() != null && updateClassViewModel.getLecturerId().length() > 0) {
				l = lecturerBO.findLecturerById(updateClassViewModel.getLecturerId());
			}
			Clazz c = new Clazz(KeyFactory.stringToKey(updateClassViewModel.getClassKey()), updateClassViewModel.getClassId(), 
					updateClassViewModel.getClassName(), updateClassViewModel.getSemester(), null, l);
			c = classBO.updateClass(c, updateClassViewModel.getSubjectId());
			DocumentIndexing.addEntityIndex(c, Constants.SEARCH_INDEX_NAME);
			session.setAttribute("msg", PropertiesUtil.getProperty("class.update.success"));
			
			if (request.getParameter("cId") == null) {
				return new ModelAndView(new RedirectView("/admin/listClasses.html?p=" + p));
			} else {
				String queryString = request.getQueryString();
				return new ModelAndView(new RedirectView("/admin/searchClasses.html?" + queryString));
			}
		}
		
	}
	
	@ModelAttribute("semesterNames")
	public Map<Integer, Integer> populateSemesters() {
		List<Semester> semesters = semesterBO.listSemester();
		Map<Integer, Integer> semesterNames = new LinkedHashMap<Integer, Integer>();
		for (Semester s : semesters) {
			semesterNames.put(s.getSemesterName(), s.getSemesterName());
		}
		return semesterNames;
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/deleteClass/{key}", method = RequestMethod.GET)
	public RedirectView deleteClass(@PathVariable("key") String key, 
			@RequestParam(value = "p", required = false, defaultValue = "1") Integer p,
			ModelMap model, HttpSession session, HttpServletRequest request) {
		
		SearchClassValueObject searchObj = buildSearchObject(request);
		int totalItems = classBO.countFoundClasses(searchObj);
		if (p < 1 || p > Util.calculateNumberOfPage(totalItems, Constants.PAGE_SIZE)) {
			p = 1;
		}
		
		int newPage = 1;
		if (request.getParameter("cId") == null) {
			totalItems = classBO.countFoundClasses(new SearchClassValueObject(null, null, null, semesterBO.getCurrentSemester().getSemesterName()));
		}
		
		classBO.deleteClass(key);
		DocumentIndexing.removeEntityIndex(key, Constants.SEARCH_INDEX_NAME);
		
		session.setAttribute("msg", PropertiesUtil.getProperty("class.delete.success"));
		newPage = Util.evaluatePageNumAfterDelete(p, totalItems, Constants.PAGE_SIZE, 1);
		
		if (request.getParameter("cId") == null) {
			return new RedirectView("/admin/listClasses.html?p=" + newPage);
		} else {
			Map<String, String> modifiedParams = new HashMap<String, String>();
			modifiedParams.put("p", String.valueOf(newPage));
			return new RedirectView("/admin/searchClasses.html?" + Util.modifyQueryString(request, modifiedParams));
		}
	}
	
	private SearchClassValueObject buildSearchObject(HttpServletRequest request) {
		String classId = request.getParameter("cId");
		String subjectId = request.getParameter("sId");
		String lecturerId = request.getParameter("lId");
		String semester = request.getParameter("semester");
		
		SearchClassValueObject searchObj = new SearchClassValueObject();
		if (classId != null && !"".equals(classId)) {
			searchObj.setClassId(classId);
		}
		if (subjectId != null && !"".equals(subjectId)) {
			searchObj.setSubjectId(subjectId);
		}
		if (lecturerId != null && !"".equals(lecturerId)) {
			searchObj.setLecturerId(lecturerId);
		}
		if (semester != null && !"".equals(semester)) {
			Integer s = 0;
			try {
				s = Integer.parseInt(semester);
				if (s == 0) {
					searchObj.setSemester(semesterBO.getCurrentSemester().getSemesterName());
				} else if (s > 0) {
					searchObj.setSemester(s);
				}
			} catch (Exception ex) {
				
			}
		} else {
			searchObj.setSemester(semesterBO.getCurrentSemester().getSemesterName());
		}
		
		return searchObj;
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/deleteClasses", method = RequestMethod.POST)
	public RedirectView deleteClasses(@RequestParam(value = "p", required = false, defaultValue = "1") Integer p,
			ModelMap model, HttpServletRequest request, HttpSession session) {
		SearchClassValueObject searchObj = buildSearchObject(request);
		int totalItems = classBO.countFoundClasses(searchObj);
		if (p < 1 || p > Util.calculateNumberOfPage(totalItems, Constants.PAGE_SIZE)) {
			p = 1;
		}
		
		String[] classKeys = request.getParameterValues("checkItem");
		if (request.getParameter("cId") == null) {
			totalItems = classBO.countFoundClasses(new SearchClassValueObject(null, null, null, semesterBO.getCurrentSemester().getSemesterName()));
		}
		int newPage = 1;
		
		if (classKeys != null && classKeys.length > 0) {
			for (String k : classKeys) {
				classBO.deleteClass(k);
			}
			DocumentIndexing.removeEntityIndexes(new ArrayList<String>(Arrays.asList(classKeys)), Constants.SEARCH_INDEX_NAME);
			session.setAttribute("msg", PropertiesUtil.getProperty("class.delete.success"));
			newPage = Util.evaluatePageNumAfterDelete(p, totalItems, Constants.PAGE_SIZE, classKeys.length);
		}
		
		if (request.getParameter("cId") == null) {
			return new RedirectView("/admin/listClasses.html?p=" + newPage);
		} else {
			Map<String, String> modifiedParams = new HashMap<String, String>();
			modifiedParams.put("p", String.valueOf(newPage));
			return new RedirectView("/admin/searchClasses.html?" + Util.modifyQueryString(request, modifiedParams));
		}
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/searchClasses", method = RequestMethod.GET)
	public String searchClasses(@RequestParam(value = "cId", required = false, defaultValue = "") String classId,
			@RequestParam(value = "sId", required = false, defaultValue = "") String subjectId,
			@RequestParam(value = "lId", required = false, defaultValue = "") String lecturerId,
			@RequestParam(value = "semester", required = false, defaultValue = "0") int semester,
			@RequestParam(value = "p", required = false, defaultValue = "1") Integer p,
			ModelMap model) {
		SearchClassValueObject searchObj = new SearchClassValueObject();
		Map<String, String> params = new HashMap<String, String>();
		
		if (classId != null && !"".equals(classId)) {
			searchObj.setClassId(classId);
			params.put("cId", classId);
		}
		
		if (subjectId != null && !"".equals(subjectId)) {
			searchObj.setSubjectId(subjectId);
			params.put("sId", subjectId);
		}
		
		if (lecturerId != null && !"".equals(lecturerId)) {
			searchObj.setLecturerId(lecturerId);
			params.put("lId", lecturerId);
		}
		
		if (semester < 0) {
			semester = -1;
		} else if (semester == 0) {
			semester = semesterBO.getCurrentSemester().getSemesterName();
			searchObj.setSemester(semester);
		} else {
			searchObj.setSemester(semester);
		}
		params.put("semester", String.valueOf(semester));
		
		model.addAttribute("classes", classBO.searchClasses(searchObj, p, Constants.PAGE_SIZE));
		model.addAttribute("pageInfo", new PageInfo(classBO.countFoundClasses(searchObj), p));
		model.addAttribute("pageSize", Constants.PAGE_SIZE);
		model.addAttribute("semesters", semesterBO.listSemester());
		model.addAttribute("params", params);
		
		return "admin/searchClasses";
	}
	
	@PreAuthorize("hasRole('ROLE_LECTURER')")
	@RequestMapping(value = "/lecturer/listTeachClasses", method = RequestMethod.GET)
	public String listClassesOfLecturerInCurrentSemester(@RequestParam(value = "p", required = false, defaultValue = "1") Integer p, ModelMap model) {
		String lecturerId = AuthUtil.getCurrentAuthenticatedUsername();
		Integer currentSemester = semesterBO.getCurrentSemester().getSemesterName();
		SearchClassValueObject searchObj = new SearchClassValueObject(null, null, lecturerId, currentSemester);
		if (p < 1 || p > Util.calculateNumberOfPage(classBO.countFoundClasses(searchObj), Constants.PAGE_SIZE)) {
			p = 1;
		}
		
		model.addAttribute("classes", classBO.searchClasses(searchObj, p, Constants.PAGE_SIZE));
		model.addAttribute("pageInfo", new PageInfo(classBO.countFoundClasses(searchObj), p));
		model.addAttribute("pageSize", Constants.PAGE_SIZE);
		
		return "lecturer/listTeachClasses";
	}
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/listOpenedClasses", method = RequestMethod.GET)
	public String listOpenedClassesInCurrentSemester(@RequestParam(value = "p", required = false, defaultValue = "1") Integer p, ModelMap model) {
		Integer currentSemester = semesterBO.getCurrentSemester().getSemesterName();
		SearchClassValueObject searchObj = new SearchClassValueObject(null, null, null, currentSemester);
		if (p < 1 || p > Util.calculateNumberOfPage(classBO.countFoundClasses(searchObj), Constants.PAGE_SIZE)) {
			p = 1;
		}
		
		model.addAttribute("classes", classBO.searchClasses(searchObj, p, Constants.PAGE_SIZE));
		model.addAttribute("pageInfo", new PageInfo(classBO.countFoundClasses(searchObj), p));
		model.addAttribute("pageSize", Constants.PAGE_SIZE);
		
		return "student/listOpenedClasses";
	}
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/searchOpenedClasses", method = RequestMethod.GET)
	public String searchOpenedClasses(@RequestParam(value = "cId", required = false, defaultValue = "") String classId,
			@RequestParam(value = "sId", required = false, defaultValue = "") String subjectId,
			@RequestParam(value = "p", required = false, defaultValue = "1") int p, ModelMap model) {
		Integer currentSemester = semesterBO.getCurrentSemester().getSemesterName();
		SearchClassValueObject searchObj = new SearchClassValueObject(null, null, null, currentSemester);
		Map<String, String> params = new HashMap<String, String>();
		
		if (classId != null && !"".equals(classId)) {
			searchObj.setClassId(classId);
			params.put("cId", classId);
		}
		
		if (subjectId != null && !"".equals(subjectId)) {
			searchObj.setSubjectId(subjectId);
			params.put("sId", subjectId);
		}
		
		model.addAttribute("classes", classBO.searchClasses(searchObj, p, Constants.PAGE_SIZE));
		model.addAttribute("pageInfo", new PageInfo(classBO.countFoundClasses(searchObj), p));
		model.addAttribute("pageSize", Constants.PAGE_SIZE);
		model.addAttribute("params", params);
		
		return "student/searchOpenedClasses";
	}
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/getOpenedClasses", method = RequestMethod.GET)
	public String getOpenedClasses(@RequestParam(value = "cId", required = false, defaultValue = "") String classId,
			@RequestParam(value = "sId", required = false, defaultValue = "") String subjectId,
			@RequestParam(value = "p", required = false, defaultValue = "1") int p, ModelMap model) {
		Integer currentSemester = semesterBO.getCurrentSemester().getSemesterName();
		SearchClassValueObject searchObj = new SearchClassValueObject(null, null, null, currentSemester);
		Map<String, String> params = new HashMap<String, String>();
		
		if (classId != null && !"".equals(classId)) {
			searchObj.setClassId(classId);
			params.put("cId", classId);
		}
		
		if (subjectId != null && !"".equals(subjectId)) {
			searchObj.setSubjectId(subjectId);
			params.put("sId", subjectId);
		}
		
		model.addAttribute("classes", classBO.searchClasses(searchObj, p, Constants.PAGE_SIZE));
		model.addAttribute("pageInfo", new PageInfo(classBO.countFoundClasses(searchObj), p));
		model.addAttribute("pageSize", Constants.PAGE_SIZE);
		model.addAttribute("params", params);
		
		return "student/getOpenedClasses";
	}
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/registerClasses", method = RequestMethod.GET)
	public String showRegisterClasses() {
		return "student/registerClasses";
	}
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/processRegisterClasses", method = RequestMethod.POST)
	public RedirectView processRegisterClasses(HttpServletRequest request, HttpSession session) {
		String[] classKeys = request.getParameterValues("selectItem");
		if (classKeys != null && classKeys.length > 0) {
			String studentId = AuthUtil.getCurrentAuthenticatedUsername();
			List<Clazz> registeredClasses = studentBO.listClassesStudentRegistered(studentId, semesterBO.getCurrentSemester().getSemesterName());
			List<Key> registeredClassKeys = new ArrayList<Key>();
			for (Clazz c : registeredClasses) {
				registeredClassKeys.add(c.getClassKey());
			}
			StringBuilder builder = new StringBuilder();
			for (String k : classKeys) {
				String classId = classBO.findClassByKey(k).getClassId();
				if (registeredClassKeys.contains(KeyFactory.stringToKey(k))) {
					builder.append(classId).append(", ");
				} else {
					classBO.addStudentToClass(studentId, classId);
				}
			}
			
			if (builder.length() > 0) {
				String err = builder.toString().substring(0, builder.toString().trim().length() - 1);
				session.setAttribute("msg", err + " " + PropertiesUtil.getProperty("class.already.registered"));
			} else {
				session.setAttribute("msg", PropertiesUtil.getProperty("class.register.success"));
			}
		} else {
			session.setAttribute("msg", PropertiesUtil.getProperty("class.not.selected"));
		}
		
		return new RedirectView("/student/registerClasses.html?" + request.getQueryString());
	}
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/cancelRegisteredClass/{classKey}", method = RequestMethod.GET)
	public RedirectView cancelRegisteredClass(@PathVariable("classKey") String classKey, HttpSession session,
			HttpServletRequest request) {
		String studentId = AuthUtil.getCurrentAuthenticatedUsername();
		Student student = studentBO.findStudentById(studentId);
		if (student != null) {
			String studentKey = KeyFactory.keyToString(student.getStudentKey());
			classBO.deleteStudentFromClass(studentKey, classKey);
			session.setAttribute("msg", PropertiesUtil.getProperty("registeredClass.delete.success"));
		}
		
		return new RedirectView("/student/registerClasses.html?" + request.getQueryString());
	}
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/cancelRegisteredClasses", method = RequestMethod.POST)
	public RedirectView cancelRegisteredClasses(HttpServletRequest request, HttpSession session) {
		String[] classKeys = request.getParameterValues("checkItem");
		String studentId = AuthUtil.getCurrentAuthenticatedUsername();
		Student student = studentBO.findStudentById(studentId);
		if (student != null) {
			String studentKey = KeyFactory.keyToString(student.getStudentKey());
			for (String classKey : classKeys) {
				classBO.deleteStudentFromClass(studentKey, classKey);
			}
			session.setAttribute("msg", PropertiesUtil.getProperty("registeredClass.delete.success"));
		}
		
		return new RedirectView("/student/registerClasses.html?" + request.getQueryString());
	}
}
